<?php
declare (strict_types=1);

namespace app\admin\logic\site;

use app\admin\logic\system\Log;
use app\admin\model\site\PersonalData;
use app\admin\model\site\PersonalGroup as PersonalGroupModel;
use app\common\exception\LogicException;

class PersonalGroup extends PersonalGroupModel
{
    /**
     * 更新分组名称
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/11/17
     *
     * @param int    $id
     * @param string $title
     */
    public function updatedTitleById(int $id, string $title)
    {
        $group = $this->findOrFail($id);

        // 更改数据表
        $personalData = PersonalData::where('data_type', 1)
            ->where('config_id', $id)
            ->where('mhm_id', request()->mhm_id)
            ->findOrEmpty();
        if ($personalData->isEmpty()) {
            $personalData->data_type = 1;
            $personalData->config_id = $id;
            $personalData->sort      = 1;
        }

        $personalData->title = $title;

        if (!$personalData->save()) {
            throw new LogicException('更新分组失败');
        }
        // 更新成功
        Log::write('更新个人中心菜单【' . $group->getAttr('title') . '】名称', 'site_personal', 'update', true);
    }

    /**
     * 更新分组排序
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 22/02/08
     *
     * @param int $id
     * @param int $sort
     */
    public function updateSortById(int $id, int $sort)
    {
        $group = $this->findOrFail($id);

        // 更改数据表
        $personalData = PersonalData::where('data_type', 1)
            ->where('config_id', $id)
            ->where('mhm_id', request()->mhm_id)
            ->findOrEmpty();
        if ($personalData->isEmpty()) {
            $personalData->data_type = 1;
            $personalData->config_id = $id;
            $personalData->title     = $group['title'];
        }

        $personalData->sort = $sort;

        if (!$personalData->force()->save()) {
            throw new LogicException('更新排序失败');
        }
        // 更新成功
        Log::write('更新个人中心菜单【' . $group->getAttr('title') . '】排序', 'site_personal', 'update', true);
    }
}
